package com.wsz.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wsz.eduservice.pojo.Subject;
import com.wsz.eduservice.pojo.excel.SubjectData;
import com.wsz.eduservice.service.SubjectService;
import com.wsz.servicebase.exceptionhandler.MyTestException;

public class SubjectExcelListenerTest extends AnalysisEventListener<SubjectData> {

    public SubjectService subjectService;

    public SubjectExcelListenerTest() {
    }

    public SubjectExcelListenerTest(SubjectService subjectService) {
        this.subjectService = subjectService;
    }


    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData == null){
            throw new MyTestException(20001,"文件为空");
        }
        String oneSubjectName = subjectData.getOneSubjectName();
        String twoSubjectName = subjectData.getTwoSubjectName();

        Subject oneSubject = getOneSubjectData(subjectService, oneSubjectName);
        if(oneSubject == null){
            oneSubject = new Subject();
            oneSubject.setParentId("0");
            oneSubject.setTitle(oneSubjectName);
            subjectService.save(oneSubject);
        }

        Subject twoSubject = getTwoSubjectData(subjectService, twoSubjectName, oneSubject.getId());
        if(twoSubject == null){
            twoSubject = new Subject();
            twoSubject.setTitle(twoSubjectName);
            twoSubject.setParentId(oneSubject.getId());
            subjectService.save(twoSubject);
        }

    }

    public Subject getOneSubjectData(SubjectService subjectService,String name) {
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id","0");
        Subject one = subjectService.getOne(queryWrapper);
        return one;
    }


    public Subject getTwoSubjectData(SubjectService subjectService,String name,String pid) {
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id",pid);
        Subject Two = subjectService.getOne(queryWrapper);
        return Two;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
